package com.gxa.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 传入对象，并将此对象以text/json;charset=UTF-8格式输出到前端
 */
public class WriteJson {
    /**
     * 向客户端输出转化为json的数据流
     *
     * @param json_str json字符串
     * @param response HttpServletResponse对象
     */
    public static void writeJson(String json_str, HttpServletResponse response){
        // 设置输出的数据格式与
        response.setContentType("text/json;charset=UTF-8");
        // 获取输出流对象
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        out.println(json_str);
    }

    public static<T> void writeJson(T t, HttpServletResponse response){
        String json_str = JSON.toJSONString(t); // 对象转Json字符串

        // 设置输出的数据格式与
        response.setContentType("text/json;charset=UTF-8");
        // 获取输出流对象
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        out.println(json_str);
    }
}
